package com.oppodowngrader;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 管理应用配置和代理规则
 */
public class ConfigManager {
    private static final String TAG = "ConfigManager";
    private static final String CONFIG_ASSET_PATH = "config.json";
    
    private final Context context;
    private JSONObject config;
    
    // 预设的降级配置（来自proxypin-rewrites.config文件）
    private static final String DEFAULT_CONFIG = "{\n" +
            "  \"target\": \"https://iot-earbuds-cn.heytapmobi.com/v1/earphone/firmwareInfo\",\n" +
            "  \"type\": \"responseReplace\",\n" +
            "  \"replaceResponseBody\": \"{\\\"code\\\":0,\\\"data\\\":{\\\"content\\\":[{\\\"firmwareSHA256\\\":\\\"08837c325e540d4ebf4de7e7d7b3bef486203f0715fa66c6dcac96f0d0d96329\\\",\\\"name\\\":\\\"1_all_666_0.bin\\\",\\\"size\\\":\\\"1146896\\\",\\\"updateInfo\\\":\\\"1、降级115.115.100版本\\\\n2、解决已知问题，提升稳定性，建议所有用户更新\\\",\\\"url\\\":\\\"https://59-47-225-48.pd1.cjjd19.com:30443/download-cdn.cjjd19.com/123-612/b6e17dd6/1820814619-0/b6e17dd6b49e790be72d871839802a64/c-m52?v=5&t=1742556901&s=1742556901470a4d8da94df5a41d1e2fb9642c80c7&r=HALDM5&bzc=2&bzs=313831393033393537343a32333835313138343a313137323939323a30&filename=sAjt-110_0.bin&x-mf-biz-cid=05af194b-8a28-4ce8-8f2d-e1335a394609-c4937c&auto_redirect=0&cache_type=1&xmfcid=b2b6bb8f-1659-48a6-ab82-73ffb52ac93a-1-50111d3b1\\\"}],\\\"name\\\":\\\"OPPO Enco Air4 Pro\\\",\\\"productId\\\":\\\"067C10\\\",\\\"updateInfo\\\":\\\"解决已知问题，提升稳定性，建议所有用户更新\\\",\\\"version\\\":\\\"666\\\"},\\\"msg\\\":\\\"成功\\\"}\"\n" +
            "}";
    
    public ConfigManager(Context context) {
        this.context = context;
        loadConfig();
    }
    
    private void loadConfig() {
        try {
            // 尝试从资源中加载配置
            AssetManager assetManager = context.getAssets();
            try (InputStream is = assetManager.open(CONFIG_ASSET_PATH)) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                config = new JSONObject(sb.toString());
            } catch (IOException e) {
                // 如果资源文件不存在，使用默认配置
                config = new JSONObject(DEFAULT_CONFIG);
                Log.d(TAG, "使用内置默认配置");
            }
        } catch (JSONException e) {
            Log.e(TAG, "解析配置文件失败", e);
            try {
                config = new JSONObject(DEFAULT_CONFIG);
            } catch (JSONException ex) {
                Log.e(TAG, "无法加载默认配置", ex);
            }
        }
    }
    
    public String getTargetUrl() {
        try {
            return config.getString("target");
        } catch (JSONException e) {
            return "https://iot-earbuds-cn.heytapmobi.com/v1/earphone/firmwareInfo";
        }
    }
    
    public String getResponseBody() {
        try {
            return config.getString("replaceResponseBody");
        } catch (JSONException e) {
            Log.e(TAG, "获取响应体失败", e);
            return "{}";
        }
    }
}